package com.example.homework8.fragment;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.example.homework8.R;
import com.example.homework8.bean.UserInfo;
import com.example.homework8.database.UserHelper;
import com.example.homework8.utils.BitmapUtil;
import com.example.homework8.utils.SharedUtil;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link UserInfoFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class UserInfoFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public UserInfoFragment() {

    }

    private TimePickerView pvTime;
    TextView birthday;
    String imgurl ="";
    RadioButton manrad ,womanrad;

    // TODO: Rename and change types and number of parameters
    public static UserInfoFragment newInstance(String param1, String param2) {
        UserInfoFragment fragment = new UserInfoFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    UserHelper helper = null;
    EditText register_user,register_password,phoneed,classnameed;
    Button register_sure ;
    ImageView imageView,birthselect;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.register, container, false);
        //创建数据库
        helper = new UserHelper(getActivity(), "SAVE_USER1.db", null, 1);
        SQLiteDatabase database = helper.getWritableDatabase();
        view.findViewById(R.id.usernameblock).setVisibility(View.GONE);
        register_user = (EditText)  view.findViewById(R.id.edt1);
        register_password = (EditText) view.findViewById(R.id.edt2);
        manrad= (RadioButton) view.findViewById(R.id.man_rad);
        birthday = view.findViewById(R.id.birthday);
        womanrad = (RadioButton) view.findViewById(R.id.woman_rad);
        pvTime = new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                date = date;
                birthday.setText(new SimpleDateFormat("yyyy年MM月dd日 HH:mm").format(date));
            }
        }).setType(new boolean[]{true, true, true, true, true, false}).build();

        imageView = (ImageView) view.findViewById(R.id.imageView);
        birthselect = view.findViewById(R.id.imgedit);
        birthselect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pvTime.show();
            }
        });
         imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showImageDialog();
            }
        });
        register_sure = (Button) view.findViewById(R.id.btn1);
        register_sure.setText("确定修改");
        imageView.setImageURI(Uri.parse(SharedUtil.getIntance(getActivity()).readShared("imgurl","")));
        register_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UserInfo userInfo = new UserInfo();
                String name = SharedUtil.getIntance(getActivity()).readShared("loginuser","未登录");
                userInfo.setName(name);
                userInfo.setPassword(register_password.getText().toString());
                String gendre =manrad.isChecked()? "男生":"女生";
                String birth = birthday.getText().toString();
                userInfo.setPhone(birth);
                userInfo.setClassname(gendre);
                int rows = helper.update(userInfo, "name=" + name);
                if (rows > 0) {
                    SharedUtil.getIntance(getActivity()).writeShared("phone",birth);
                    SharedUtil.getIntance(getActivity()).writeShared("classname",gendre);
                    SharedUtil.getIntance(getActivity()).writeShared("imgurl",imgurl);

                    Toast.makeText(getActivity(), "修改成功", Toast.LENGTH_SHORT).show();
                    getActivity().getSupportFragmentManager()
                            .beginTransaction()
                            .replace(R.id.id_content, new MeFragment(), null)
                            .addToBackStack(null)
                            .commit();
                }
            }
        });
        return view;
    }

    private void showImageDialog() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // 以startActivityForResult的方式启动一个activity用来获取返回的结果
        startActivityForResult(intent, 1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode ==1){

            Uri uri = data.getData();
            Bitmap bitmap = null;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
            } catch (IOException e) {
                e.printStackTrace();
            }
            imageView.setImageBitmap(bitmap);
            String name = UUID.randomUUID().toString().substring(24)+".png";
            imgurl =  BitmapUtil.saveImgToDisk(name,bitmap);
        }
    }
}